package com.aiyun.securiy.login.security.custom;

import com.aiyun.securiy.login.security.UserList;

import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

	private final LoginSuccessHandler loginSuccessHandler;

	private final LoginFailureHandler loginFailureHandler;

	private final UserList userList;

	private final CustomAuthenticationProvider customAuthenticationProvider;

	public CustomAuthenticationSecurityConfig(LoginSuccessHandler loginSuccessHandler, LoginFailureHandler loginFailureHandler, UserList userList, CustomAuthenticationProvider customAuthenticationProvider) {
		this.loginSuccessHandler = loginSuccessHandler;
		this.loginFailureHandler = loginFailureHandler;
		this.userList = userList;
		this.customAuthenticationProvider = customAuthenticationProvider;
	}

	@Override
	public void configure(HttpSecurity httpSecurity) throws Exception {
		CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter();
		customAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
		customAuthenticationFilter.setAuthenticationFailureHandler(loginFailureHandler);
		customAuthenticationFilter.setAuthenticationManager(new ProviderManager(customAuthenticationProvider));

		httpSecurity
				.addFilterAfter(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
				.addFilterBefore(new CustomRequestFilter(userList), UsernamePasswordAuthenticationFilter.class)
				.authenticationProvider(customAuthenticationProvider)
		        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
	}
}
